<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true" label-width="120px">
      <el-form-item label="统计类型">
        <el-select
          v-model="type"
          placeholder="统计类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in typeList"
            :key="dict.name"
            :label="dict.name"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="筛选时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="timestamp"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 商家 -->
    <el-table
      v-loading="loading"
      v-if="type == 0"
      :data="tableData"
      stripe
      border
      style="width: 100%"
      :default-sort="{ prop: 'saleNum', order: 'descending' }"
      @row-click="handleRowClickShop"
    >
      <el-table-column prop="classifyId" label="分类ID" width="120" sortable>
      </el-table-column>
      <el-table-column prop="classifyName" label="分类名称" sortable>
      </el-table-column>
      <el-table-column prop="saleNum" label="销量" width="180" sortable>
      </el-table-column>
      <el-table-column prop="salePrice" label="销售价格" width="200" sortable>
      </el-table-column>
    </el-table>

    <!-- 商铺分类详情 -->
    <el-dialog
      :title="curClassifyName"
      :visible.sync="openShop"
      width="800px"
      append-to-body
    >
      <el-table
        :data="shopDataList"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'saleNum', order: 'descending' }"
      >
        <el-table-column prop="goodsName" label="商品名称" sortable>
        </el-table-column>
        <el-table-column prop="saleNum" label="销量" width="120" sortable>
        </el-table-column>
        <el-table-column prop="salePrice" label="销售价格" width="120" sortable>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 配送点 -->
    <el-table
      v-loading="loading"
      v-if="type == 1"
      :data="tableData"
      stripe
      border
      style="width: 100%"
      :default-sort="{ prop: 'orderNum', order: 'descending' }"
    >
      <el-table-column prop="pointId" label="配送点" width="120" sortable>
      </el-table-column>
      <el-table-column prop="pointName" label="配送点名称" sortable>
      </el-table-column>
      <el-table-column prop="orderNum" label="总订单量" width="180" sortable>
      </el-table-column>
      <el-table-column prop="freeNum" label="免费订单量" width="180" sortable>
      </el-table-column>
      <el-table-column
        prop="orderAllMoeny"
        label="订单总额"
        width="200"
        sortable
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click.stop.native="handleRowClickPoint(scope.row)"
            >商品销售详情（包含发货和未发货）</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click.stop.native="handleRowClickPoint2(scope.row)"
            >商品及奖品销售详情（已发货）</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click.stop.native="handleJumpStatisticsUser(scope.row)"
            >用户消费情况</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click.stop.native="handleJumpStatisticsOrder(scope.row)"
            >订单筛选列表</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 商品销售详情（包含发货和未发货） -->
    <el-dialog
      :title="curPointName"
      :visible.sync="openPoint"
      width="800px"
      append-to-body
    >
      <el-form
        :model="pointsParams"
        ref="pointType"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="商品分类" prop="type">
          <el-select
            v-model="pointsParams.type"
            placeholder="商品分类"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="dict in pointsType"
              :key="dict.name"
              :label="dict.name"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        :data="pointDataList"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'saleNum', order: 'descending' }"
      >
        <el-table-column
          v-if="pointsParams.type == 10"
          prop="goodsName"
          label="商品名称"
          sortable
        >
        </el-table-column>
        <el-table-column
          v-if="pointsParams.type == 20"
          prop="classifyName"
          label="分类名称"
          sortable
        >
        </el-table-column>
        <el-table-column prop="saleNum" label="销量" width="120" sortable>
        </el-table-column>
        <el-table-column prop="salePrice" label="销售价格" width="120" sortable>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 商品及奖品销售详情（已发货） -->
    <el-dialog
      :title="curPointName"
      :visible.sync="openPoint2"
      width="800px"
      append-to-body
    >
      <el-form
        :model="pointsOrderParams"
        ref="pointType"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="筛选时间">
          <el-date-picker
            v-model="pointsParams2DateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-table
        :data="pointDataList2"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'saleNum', order: 'descending' }"
      >
        <el-table-column
          prop="goodsName"
          label="商品名称"
          sortable
        >
        </el-table-column>
        <el-table-column prop="attributes" label="SKU" sortable>
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          sortable
        >
          <template slot-scope="scope" width="120">
              <div v-if="scope.row.type == 10">普通商品</div>
              <div v-else-if="scope.row.type == 20">礼品</div>
              <div v-else>其它</div>
            </template>
        </el-table-column>
        <el-table-column prop="saleNum" label="销量" width="120" sortable>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 配送点订单详情 -->
    <el-dialog
      :title="curPointName"
      :visible.sync="openPointOrder"
      width="800px"
      append-to-body
    >
      <el-form
        :model="pointsOrderParams"
        ref="pointType"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="筛选时间">
          <el-date-picker
            v-model="pointsOrderDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <el-table
        :data="pointOrderDataList"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'saleNum', order: 'descending' }"
        @row-click="handleRowClickOrder"
      >
        <el-table-column prop="ordersNo" label="订单编号" sortable>
        </el-table-column>
        <el-table-column prop="ordersId" label="订单ID" sortable>
        </el-table-column>
        <el-table-column prop="payType" label="支付方式" sortable>
          <template slot-scope="scope">
            <div v-if="scope.row.payType == 'wxpay'">微信支付</div>
            <div v-else-if="scope.row.payType == 'alipay'">支付宝支付</div>
            <div v-else>其它支付</div>
          </template>
        </el-table-column>
        <el-table-column prop="payTime" label="支付时间" sortable>
        </el-table-column>
        <el-table-column prop="userId" label="收货人ID" sortable>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  goodsStatisticsPoint,
  goodsStatisticsClassify,
  orderStatisticsPoint,
  goodsStatisticsList,
  listByTime,
  singlePointSale,
} from "@/api/system/statistics";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Statistics",
  data() {
    return {
      typeList: [
        {
          value: 0,
          name: "商铺",
        },
        {
          value: 1,
          name: "配送点",
        },
      ],
      pointsType: [
        {
          value: 10,
          name: "单商品",
        },
        {
          value: 20,
          name: "分类商品",
        },
      ],
      pointsParams: {
        type: 10,
        id: 0,
      },
      pointsParams2: {
        beginTime: "",
        endTime: "",
        id: 0,
      },
      pointsOrderParams: {
        beginTime: "",
        endTime: "",
        id: "",
        pageNum: 1,
        pageSize: 10,
      },
      pointsParams2DateRange: [],
      shopParams: {
        classifyId: "",
      },
      queryParams: {
        shopId: 6,
      },
      loading: false,
      type: 0,
      openShop: false,
      openPoint: false,
      openPoint2: false,
      openPointOrder: false,
      curPointName: "",
      curClassifyName: "",
      dateRange: [],
      pointsOrderDateRange: [],
      tableData: [],
      pointDataList: [],
      pointDataList2: [],
      pointOrderDataList: [],
      shopDataList: [],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    type() {
      this.getList();
    },
    pointsParams: {
      handler() {
        this.getGoodsStatisticsPoint();
      },
      deep: true,
    },
    pointsOrderDateRange(val) {
      let data = {};
      if (null != val && "" != val) {
        data.beginTime = val[0] ? val[0] : undefined;
        data.endTime = val[1] ? val[1] : undefined;
      }
      this.pointsOrderParams = {
        ...this.pointsOrderParams,
        ...data,
      };
    },
    pointsParams2DateRange(val) {
      let data = {};
      if (null != val && "" != val) {
        data.beginTime = val[0] ? val[0] : undefined;
        data.endTime = val[1] ? val[1] : undefined;
      }
      this.pointsParams2 = {
        ...this.pointsParams2,
        ...data,
      };
    },
    pointsParams2: {
      handler() {
        this.getSinglePointSale();
      },
      deep: true,
    },
    pointsOrderParams: {
      handler() {
        this.getPointOrderList();
      },
      deep: true,
    },
  },
  methods: {
    // 商品销售详情（包含发货和未发货）
    handleRowClickPoint(row) {
      this.openPoint = true;
      this.curPointName = row.pointName;
      this.pointsParams.id = row.pointId;
      this.getGoodsStatisticsPoint();
    },

    getGoodsStatisticsPoint() {
      goodsStatisticsPoint({
        shopId: 6,
        pointId: this.pointsParams.id,
        index: this.pointsParams.type,
      }).then((res) => {
        this.pointDataList = res.data.list;
      });
    },

    // 商品及奖品销售详情（已发货）
    handleRowClickPoint2(row) {
      this.openPoint2 = true;
      this.curPointName = row.pointName;
      this.pointsParams2.id = row.pointId;

      let now = new Date();
      let endTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
      now.setDate(now.getDate() - 7);
      let beginTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
      this.pointsParams2DateRange = [beginTime, endTime];
    },
    getSinglePointSale() {
      singlePointSale({
        shopId: 6,
        pointId: this.pointsParams2.id,
        beginTime: this.pointsParams2.beginTime,
        endTime: this.pointsParams2.endTime,
      }).then((res) => {
        this.pointDataList2 = res.data;
      });
    },

    handleRowClickShop(row, column, event) {
      this.openShop = true;
      this.curClassifyName = row.classifyName;
      this.shopParams.classifyId = row.classifyId;
      goodsStatisticsList({
        shopId: 6,
        classifyId: this.shopParams.classifyId,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
      }).then((res) => {
        this.shopDataList = res.rows;
      });
    },
    handleJumpStatisticsOrder(row) {
      this.openPointOrder = true;
      this.curPointName = row.pointName;
      this.pointsOrderParams.id = row.pointId;

      let now = new Date();
      let endTime =
        now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
      now.setDate(now.getDate() - 7);
      let beginTime =
        now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
      this.pointsOrderDateRange = [beginTime, endTime];
    },

    getPointOrderList() {
      listByTime(this.pointsOrderParams).then((res) => {
        this.loading = false;
        this.pointOrderDataList = res.rows;
      });
    },

    getList() {
      this.loading = true;
      let search = {
        startTime: "",
        endTime: "",
      };
      if (null != this.dateRange && "" != this.dateRange) {
        console.log(this.dateRange);
        search.startTime = this.dateRange[0] ? this.dateRange[0] : undefined;
        search.endTime = this.dateRange[1] ? this.dateRange[1] : undefined;
      }
      this.queryParams = {
        ...this.queryParams,
        ...search,
      };
      if (this.type == 1) {
        orderStatisticsPoint(this.queryParams).then((res) => {
          this.loading = false;
          this.tableData = res.rows;
        });
      } else if (this.type == 0) {
        goodsStatisticsClassify(this.queryParams).then((res) => {
          this.loading = false;
          this.tableData = res.rows;
        });
      }
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleJumpStatisticsUser(row) {
      this.$router.push({
        path: `/statistics/user`,
        query: {
          pointId: row.pointId,
          pointName: row.pointName,
        },
      });
    },
    handleRowClickOrder(row) {
      this.$router.push({
        path: `/order/orderList`,
        query: {
          openDetail: true,
          ordersId: row.ordersId,
        },
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUser(queryParams);
        })
        .then((response) => {
          this.download(response.data);
        })
        .catch(function () {});
    },
  },
};
</script>
